package de.ttf.ts.ctx;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import de.ttf.ts.shared.PersistenceLifecycleAware;

public class PersistenceLifecycleInterceptor implements MethodInterceptor {

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object result = null;
        Throwable exception = null;
        try {
            result = invocation.proceed();
        } catch (Throwable e) {
            exception = e;
        }
        boolean success = exception == null;

        if (invocation.getThis() instanceof PersistenceLifecycleAware) {
            ((PersistenceLifecycleAware) invocation.getThis()).after(success);
        }

        if (!success) {
            throw exception;
        }
        return result;
    }

}
